package com.nf.practice.distincttest;

import org.junit.jupiter.api.Test;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class DisMapTest3 {

    @Test
    public void test() {
        Map<String,Object> stu1= new HashMap<>();
        Map<String,Object> stu2= new HashMap<>();
        Map<String,Object> stu3= new HashMap<>();
        Map<String,Object> stu4= new HashMap<>();
        stu1.put("appNoTrigger","1001");
        stu1.put("accLmt",1800);
        stu1.put("ruleVariableDesc","重复了没");

        stu2.put("appNoTrigger","1002");
        stu2.put("accLmt",1800);
        stu2.put("ruleVariableDesc","没有重复");

        stu3.put("appNoTrigger","1003");
        stu3.put("accLmt",1800);
        stu3.put("ruleVariableDesc","依然没有重复");

        stu4.put("appNoTrigger","1001");
        stu4.put("accLmt",1800);
        stu4.put("ruleVariableDesc","重复了没");

        List<Map<String,Object>> stuList = new ArrayList<>();
        stuList.add(stu1);
        stuList.add(stu2);
        stuList.add(stu3);
        stuList.add(stu4);

        System.out.println("原始集合");
        stuList.forEach(System.out::println);

        List<Object> deleteDuplicatedKeys = new ArrayList<>();
        deleteDuplicatedKeys.add("appNoTrigger");
        deleteDuplicatedKeys.add("ruleVariableDesc");

        List<Map<String,Object>> result = deleteDuplicatedMapFromListByKeys(stuList,deleteDuplicatedKeys);
        System.out.println("-----------------------------\n去重参数:" +deleteDuplicatedKeys+ "-去重后集合:");
        result.forEach(System.out::println);
    }

    /**
     * 该方法可根据指定字段对List<Map>中的数据去重
     * @param originMapList 源Map数组
     * @param keys 依据的去重字段
     * @return
     */
    private List<Map<String,Object>> deleteDuplicatedMapFromListByKeys(List<Map<String,Object>> originMapList, List keys){
        Map tempMap = new HashMap();
        for (Map originMap : originMapList) {
            String objHashCode = "";
            for (Object key : keys) {
                String value = originMap.get(key) != null ? originMap.get(key).toString()  : "";
                objHashCode += value.hashCode();
            }
            tempMap.put(objHashCode,originMap);
        }
        List valueList = new ArrayList<>(tempMap.values());
        return valueList;
    }


}
